package com.zidongxiangxi.clock.server.task;

import com.zidongxiangxi.clock.server.business.ClockBusiness;
import com.zidongxiangxi.clock.server.repository.entity.Clock;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;

import java.util.concurrent.ExecutorService;

/**
 * 闹钟task
 *
 * @author chenxudong
 * @date 2021/06/07
 */
public class ClockTimerTask implements TimerTask, Runnable {
    private final ClockBusiness clockBusiness;
    private final ExecutorService executorService;
    private final Clock clock;
    private Timeout timeout;

    public ClockTimerTask(ExecutorService executorService, ClockBusiness clockBusiness,
        Clock clock) {
        this.executorService = executorService;
        this.clockBusiness = clockBusiness;
        this.clock = clock;
    }

    @Override
    public void run(Timeout timeout) throws Exception {
        this.timeout = timeout;
        executorService.submit(this);
    }

    @Override
    public void run() {
        if (timeout.isCancelled()) {
            return;
        }
        clockBusiness.ringClock(clock);
    }

}
